from django.conf import settings
import smtplib
from email.mime.text import MIMEText
from django.template import RequestContext, loader
from email.MIMEMultipart import MIMEMultipart
from smtplib import SMTP
import email.Charset
from django.utils.encoding import *
from django.template.loader import render_to_string
from email.MIMEBase import MIMEBase
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

charset='utf-8'

email.Charset.add_charset(charset, email.Charset.SHORTEST, None, None)

def send_html_mail(
    subject, sender="", recip="", context=None, 
    html_template="", sender_name="",
    html_content="", recip_list=None, sender_formatted=""
):
    if not context: context = {}

    if html_template:
        html = render_to_string(html_template, context)
    else: 
        html = html_content
    if not recip_list: recip_list = []

    if recip: recip_list.append(recip)
    
    if not sender_formatted:
        sender_formatted = "%s <%s>" % (sender_name, sender) 

    for recip in recip_list:
        msgRoot = MIMEMultipart('related')
        msgRoot['Subject'] = subject.encode("utf8", 'xmlcharrefreplace')
        msgRoot['From'] = sender_formatted.encode("utf8", 'xmlcharrefreplace')
        msgRoot['To'] = recip.encode("utf8", 'xmlcharrefreplace')
        msgRoot.preamble = 'This is a multi-part message in MIME format.'

        msgAlternative = MIMEMultipart('alternative')
        msgRoot.attach(msgAlternative)

        msgAlternative.attach(MIMEText(smart_str(html), 'html', _charset=charset))

        server = smtplib.SMTP()
        server.connect(settings.EMAIL_HOST, settings.EMAIL_PORT)
        server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
        server.sendmail(sender, recip_list, msgRoot.as_string())


def render(context, template):
    from django.template import loader, Context
    if template:
        t = loader.get_template(template)
        return t.render(Context(context))
    return context


def send_mail_html(to_email, subject, template, context):
	sender = settings.DEFAULT_FROM_EMAIL
	send_html_mail(subject, recip=to_email, sender=sender, html_template=template, context=context)


def send_text_mail(from_email, to, subject, text, files):
	if not isinstance(to, basestring):
		for item in to:
			send_text_mail(from_email, item, subject, text, files)
		return
		
	msg = MIMEMultipart()
	msg['From'] = from_email
	msg['To'] = to
	msg['Date'] = formatdate(localtime=True)
	msg['Subject'] = subject

	msg.attach(MIMEText(text))

	for file in files:
		part = MIMEBase('application', "octet-stream")
		part.set_payload(open(file, "rb").read())
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
		msg.attach(part)

	server = smtplib.SMTP()
	server.connect(settings.EMAIL_HOST)
	server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
	server.sendmail(from_email, [to], msg.as_string())
	server.close()
	

